package com.tianhai.db;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.tianhai.db.parser.ast.CreateTableStatement;
import com.tianhai.db.parser.ast.DeleteStatement;
import com.tianhai.db.parser.ast.InsertStatement;
import com.tianhai.db.parser.ast.SelectStatement;
import com.tianhai.db.parser.ast.UpdateStatement;

/**
 * Executor测试类 - 测试所有CRUD功能
 */
public class ExecutorTest {
    
    public static void main(String[] args) {
        System.out.println("========================================");
        System.out.println("       Executor CRUD 功能测试");
        System.out.println("========================================\n");
        
        Executor executor = new Executor();
        int totalTests = 0;
        int passedTests = 0;
        
        // 测试1: CREATE TABLE
        System.out.println("【测试1】CREATE TABLE");
        try {
            List<CreateTableStatement.ColumnDefinition> columns = Arrays.asList(
                new CreateTableStatement.ColumnDefinition("id", CreateTableStatement.DataType.INT),
                new CreateTableStatement.ColumnDefinition("name", CreateTableStatement.DataType.VARCHAR, 50),
                new CreateTableStatement.ColumnDefinition("age", CreateTableStatement.DataType.INT)
            );
            CreateTableStatement createStmt = new CreateTableStatement("users", columns);
            Executor.ExecuteResult result = executor.execute(createStmt);
            
            if (result.isSuccess()) {
                System.out.println("✓ " + result.getMessage());
                passedTests++;
            } else {
                System.out.println("✗ " + result.getMessage());
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试2: INSERT - 插入第一条数据
        System.out.println("【测试2】INSERT - 插入数据");
        try {
            InsertStatement insertStmt = new InsertStatement(
                "users",
                Arrays.asList("id", "name", "age"),
                Arrays.asList(1, "张三", 25)
            );
            Executor.ExecuteResult result = executor.execute(insertStmt);
            
            if (result.isSuccess() && result.getAffectedRows() == 1) {
                System.out.println("✓ " + result.getMessage());
                passedTests++;
            } else {
                System.out.println("✗ 插入失败");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试3: INSERT - 批量插入
        System.out.println("【测试3】INSERT - 批量插入多条数据");
        try {
            List<Object[]> testData = Arrays.asList(
                new Object[]{2, "李四", 30},
                new Object[]{3, "王五", 28},
                new Object[]{4, "赵六", 35},
                new Object[]{5, "钱七", 22}
            );
            
            int insertCount = 0;
            for (Object[] data : testData) {
                InsertStatement stmt = new InsertStatement(
                    "users",
                    Arrays.asList("id", "name", "age"),
                    Arrays.asList(data)
                );
                if (executor.execute(stmt).isSuccess()) {
                    insertCount++;
                }
            }
            
            if (insertCount == testData.size()) {
                System.out.println("✓ 成功插入 " + insertCount + " 条数据");
                passedTests++;
            } else {
                System.out.println("✗ 部分插入失败");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试4: SELECT * - 查询所有数据
        System.out.println("【测试4】SELECT * - 查询所有数据");
        try {
            SelectStatement selectStmt = new SelectStatement(null, "users", null, null, null);
            Executor.ExecuteResult result = executor.execute(selectStmt);
            
            if (result.isSuccess() && result.getResultSet() != null) {
                System.out.println("✓ " + result.getMessage());
                System.out.println("  查询到 " + result.getResultSet().size() + " 条记录:");
                for (Map<String, Object> row : result.getResultSet()) {
                    System.out.println("  " + row);
                }
                if (result.getResultSet().size() == 5) {
                    passedTests++;
                }
            } else {
                System.out.println("✗ 查询失败");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试5: SELECT with WHERE - 条件查询
        System.out.println("【测试5】SELECT with WHERE - 条件查询");
        try {
            SelectStatement.WhereClause where = new SelectStatement.WhereClause(
                Arrays.asList(new SelectStatement.Condition("age", SelectStatement.Operator.GREATER_THAN, 25))
            );
            SelectStatement selectStmt = new SelectStatement(null, "users", where, null, null);
            Executor.ExecuteResult result = executor.execute(selectStmt);
            
            if (result.isSuccess() && result.getResultSet() != null) {
                System.out.println("✓ " + result.getMessage());
                System.out.println("  查询到 age > 25 的记录 " + result.getResultSet().size() + " 条:");
                for (Map<String, Object> row : result.getResultSet()) {
                    System.out.println("  " + row);
                }
                if (result.getResultSet().size() == 3) {
                    passedTests++;
                }
            } else {
                System.out.println("✗ 查询失败");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试6: SELECT with 列投影
        System.out.println("【测试6】SELECT - 指定列查询");
        try {
            SelectStatement selectStmt = new SelectStatement(
                Arrays.asList("name", "age"), "users", null, null, null
            );
            Executor.ExecuteResult result = executor.execute(selectStmt);
            
            if (result.isSuccess() && result.getResultSet() != null) {
                System.out.println("✓ " + result.getMessage());
                System.out.println("  查询到 " + result.getResultSet().size() + " 条记录:");
                for (Map<String, Object> row : result.getResultSet()) {
                    System.out.println("  " + row);
                }
                passedTests++;
            } else {
                System.out.println("✗ 查询失败");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试7: SELECT with LIMIT
        System.out.println("【测试7】SELECT with LIMIT - 限制结果数量");
        try {
            SelectStatement selectStmt = new SelectStatement(null, "users", null, null, 3);
            Executor.ExecuteResult result = executor.execute(selectStmt);
            
            if (result.isSuccess() && result.getResultSet() != null && result.getResultSet().size() == 3) {
                System.out.println("✓ " + result.getMessage());
                System.out.println("  LIMIT 3, 返回 " + result.getResultSet().size() + " 条记录");
                passedTests++;
            } else {
                System.out.println("✗ LIMIT功能异常");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试8: UPDATE - 更新数据
        System.out.println("【测试8】UPDATE - 更新数据");
        try {
            SelectStatement.WhereClause where = new SelectStatement.WhereClause(
                Arrays.asList(new SelectStatement.Condition("id", SelectStatement.Operator.EQUAL, 1))
            );
            UpdateStatement updateStmt = new UpdateStatement(
                "users",
                Arrays.asList(new UpdateStatement.Assignment("age", 26)),
                where
            );
            Executor.ExecuteResult result = executor.execute(updateStmt);
            
            if (result.isSuccess() && result.getAffectedRows() == 1) {
                System.out.println("✓ " + result.getMessage());
                
                // 验证更新
                SelectStatement verifyStmt = new SelectStatement(null, "users", where, null, null);
                Executor.ExecuteResult verifyResult = executor.execute(verifyStmt);
                if (verifyResult.getResultSet().get(0).get("age").equals(26)) {
                    System.out.println("  验证成功: age已更新为26");
                    passedTests++;
                }
            } else {
                System.out.println("✗ 更新失败");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试9: UPDATE - 批量更新
        System.out.println("【测试9】UPDATE - 批量更新");
        try {
            SelectStatement.WhereClause where = new SelectStatement.WhereClause(
                Arrays.asList(new SelectStatement.Condition("age", SelectStatement.Operator.LESS_THAN, 30))
            );
            UpdateStatement updateStmt = new UpdateStatement(
                "users",
                Arrays.asList(new UpdateStatement.Assignment("age", 30)),
                where
            );
            Executor.ExecuteResult result = executor.execute(updateStmt);
            
            if (result.isSuccess() && result.getAffectedRows() > 0) {
                System.out.println("✓ " + result.getMessage() + ", 影响 " + result.getAffectedRows() + " 行");
                passedTests++;
            } else {
                System.out.println("✗ 更新失败");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试10: DELETE - 删除数据
        System.out.println("【测试10】DELETE - 删除指定数据");
        try {
            SelectStatement.WhereClause where = new SelectStatement.WhereClause(
                Arrays.asList(new SelectStatement.Condition("id", SelectStatement.Operator.EQUAL, 5))
            );
            DeleteStatement deleteStmt = new DeleteStatement("users", where);
            Executor.ExecuteResult result = executor.execute(deleteStmt);
            
            if (result.isSuccess() && result.getAffectedRows() == 1) {
                System.out.println("✓ " + result.getMessage());
                
                // 验证删除
                SelectStatement verifyStmt = new SelectStatement(null, "users", null, null, null);
                Executor.ExecuteResult verifyResult = executor.execute(verifyStmt);
                if (verifyResult.getResultSet().size() == 4) {
                    System.out.println("  验证成功: 剩余 " + verifyResult.getResultSet().size() + " 条记录");
                    passedTests++;
                }
            } else {
                System.out.println("✗ 删除失败");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试11: WHERE多条件测试
        System.out.println("【测试11】WHERE - 多条件查询");
        try {
            SelectStatement.WhereClause where = new SelectStatement.WhereClause(
                Arrays.asList(
                    new SelectStatement.Condition("age", SelectStatement.Operator.GREATER_THAN_OR_EQUAL, 30),
                    new SelectStatement.Condition("id", SelectStatement.Operator.LESS_THAN, 5)
                )
            );
            SelectStatement selectStmt = new SelectStatement(null, "users", where, null, null);
            Executor.ExecuteResult result = executor.execute(selectStmt);
            
            if (result.isSuccess() && result.getResultSet() != null) {
                System.out.println("✓ " + result.getMessage());
                System.out.println("  查询到 age >= 30 AND id < 5 的记录 " + result.getResultSet().size() + " 条:");
                for (Map<String, Object> row : result.getResultSet()) {
                    System.out.println("  " + row);
                }
                passedTests++;
            } else {
                System.out.println("✗ 查询失败");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试12: 操作不存在的表
        System.out.println("【测试12】错误处理 - 操作不存在的表");
        try {
            SelectStatement selectStmt = new SelectStatement(null, "nonexistent", null, null, null);
            Executor.ExecuteResult result = executor.execute(selectStmt);
            
            if (!result.isSuccess() && result.getMessage().contains("不存在")) {
                System.out.println("✓ 正确处理: " + result.getMessage());
                passedTests++;
            } else {
                System.out.println("✗ 错误处理异常");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 测试13: 创建重复表
        System.out.println("【测试13】错误处理 - 创建重复表");
        try {
            List<CreateTableStatement.ColumnDefinition> columns = Arrays.asList(
                new CreateTableStatement.ColumnDefinition("id", CreateTableStatement.DataType.INT)
            );
            CreateTableStatement createStmt = new CreateTableStatement("users", columns);
            Executor.ExecuteResult result = executor.execute(createStmt);
            
            if (!result.isSuccess() && result.getMessage().contains("已存在")) {
                System.out.println("✓ 正确处理: " + result.getMessage());
                passedTests++;
            } else {
                System.out.println("✗ 错误处理异常");
            }
        } catch (Exception e) {
            System.out.println("✗ 异常: " + e.getMessage());
        }
        totalTests++;
        System.out.println();
        
        // 最终结果统计
        System.out.println("========================================");
        System.out.println("           测试结果汇总");
        System.out.println("========================================");
        System.out.println("总测试数: " + totalTests);
        System.out.println("通过数: " + passedTests);
        System.out.println("失败数: " + (totalTests - passedTests));
        System.out.println("通过率: " + String.format("%.1f%%", passedTests * 100.0 / totalTests));
        System.out.println("----------------------------------------");
        
        if (passedTests == totalTests) {
            System.out.println("✓✓✓ 所有测试通过！");
        } else {
            System.out.println("✗✗✗ 部分测试失败");
        }
        System.out.println("========================================\n");
    }
}
